<template>
  <!-- 按钮组件 -->
  <a-spin :spinning="btnLoading" size="large" tip="数据导出中...">
    <common-search :show-item="2" :col-layout="{xxl: 6, xl:8, lg: 8, md: 12, sm: 24, xs: 24}" v-model="query" :formItems="formItems" @search="search" @reset="reset"></common-search>
    <a-button @click="toExport" type="primary" :loading="btnLoading" v-modulePerm="['orderList:export']">
      <template #icon>
        <DownloadOutlined />
      </template>
      导出
    </a-button>
    <common-table
          class="table-container"
          :columns="columns"
          :dataSource="handleDataList"
          v-model:localPagination="page"
          @paginationChange="onPageChange"
          :slots="['basicItem', 'accountItem','skuItemList', 'addressItem', 'orderSourceItem']"
          v-model:loading="loading"
          :rowKey="(record) => record.id"
          :scroll="{ x: 2000 }"
          :customHeaderRow="()=>{
            return {
              style:{
                backgroundColor:'#6c9ce4'
              }
            }
          }"
      >
        <template #basicItem="{ record }">
          <Descriptions style="margin:20px 5px 20px 5px" :singleLine="['下单时间','下单邮箱']" :link="['订单']" :columnMap="baseColumnsMap" :columns="baseColumns" :dataList="record.basicItem"/>
        </template>
        <template #accountItem="{ record }">
          <Descriptions :isMoney="true" :columnMap="amountColumnsMap" :columns="amountColumns" :dataList="record.accountItem"/>
        </template>
        <template #skuItemList="{ record }">
          <div style="display: flex;align-items: center;justify-content: space-between;">
            <span style="font-weight: 500;font-size: 16px">原始SKU</span>
            <a v-if="openShowMoreSkuItem(record,'showMoreSourceSku','sourceSkuList')" style="color: #1890ff;cursor: pointer" @click="showMoreSkuItem(record,'open','showMoreSourceSku')">
              展开
            </a>
            <a v-if="closeShowMoreSkuItem(record,'showMoreSourceSku')" style="color: #1890ff;cursor: pointer" @click="showMoreSkuItem(record,'close','showMoreSourceSku')">
              收起
            </a>
          </div>
          <template v-if="record.sourceAndProductSkuItem?.sourceSkuList.length <= 3">
            <span v-for="(item,index) in record.sourceAndProductSkuItem?.sourceSkuList">
              <span v-if="index !== record.sourceAndProductSkuItem?.sourceSkuList.length-1">
                {{item + ','}}
              </span>
              <span v-else>
                {{item}}
              </span>
            </span>
          </template>
          <template v-else>
            <span v-for="(item,index) in record.sourceAndProductSkuItem?.sourceSkuList.slice(0,10)">
              <span v-if="index !== record.sourceAndProductSkuItem?.sourceSkuList.length-1">
                {{item + ','}}
              </span>
              <span v-else>
                {{item}}
              </span>
            </span>
            <div v-if="record.sourceAndProductSkuItem?.showMoreSourceSku">
              <span v-for="(item,index) in record.sourceAndProductSkuItem?.sourceSkuList.slice(10)">
                 <span v-if="index !== record.sourceAndProductSkuItem?.sourceSkuList.length-1">
                   {{item + ','}}
                 </span>
                 <span v-else>
                   {{item}}
                 </span>
              </span>
            </div>
          </template>
          <br/>
          <br/>
          <div style="display: flex;align-items: center;justify-content: space-between;">
            <span style="font-weight: 500;font-size: 16px;">标准产品</span>
            <a v-if="openShowMoreSkuItem(record,'showMoreSkuItem','skuItemList')" style="color: #1890ff;cursor: pointer" @click="showMoreSkuItem(record,'open','showMoreSkuItem')">
              展开
            </a>
            <a v-if="closeShowMoreSkuItem(record,'showMoreSkuItem')" style="color: #1890ff;cursor: pointer" @click="showMoreSkuItem(record,'close','showMoreSkuItem')">
              收起
            </a>
          </div>
          <template v-if="record.sourceAndProductSkuItem?.skuItemList.length <= 10">
            <div v-for="item in record.sourceAndProductSkuItem?.skuItemList">
              {{item.productSku + ' x ' + item.qty}}
            </div>
          </template>
          <template v-else>
            <div v-for="item in record.sourceAndProductSkuItem?.skuItemList.slice(0,10)">
              {{item.productSku + ' x ' + item.qty}}
            </div>
            <div v-if="record.sourceAndProductSkuItem?.showMoreSkuItem">
              <div v-for="item in record.sourceAndProductSkuItem?.skuItemList.slice(10)">
                {{item.productSku + ' x ' + item.qty}}
              </div>
            </div>
          </template>
        </template>
        <template #addressItem="{ record }">
          <Descriptions :singleLine="['国家','地址','姓名','电话','邮箱']" :columnMap="addressColumnsMap" :columns="addressColumns" :dataList="record.addressItem"/>
        </template>
        <template #orderSourceItem="{ record }">
          <Descriptions :singleLine="['神策用户','自定义归因','末因','首因']"  :columnMap="causeColumnsMap" :columns="causeColumns" :dataList="record.orderSourceItem"/>
        </template>
      </common-table>
  </a-spin>
</template>
<script setup>

import CommonSearch from "@/components/commonSearch/index.vue";
import CommonTable from "@/components/commonTable/index.vue";
import {useSearchTable} from "@/hooks/table/useSearchTable";
import {ref,onMounted,reactive} from "vue";
import Descriptions from "@/components/descriptions/tableDes.vue";
import {
  baseColumnsMap,
  baseColumns,
  amountColumns,
  amountColumnsMap,
  addressColumnsMap,
  addressColumns, causeColumnsMap, causeColumns
} from "@utils/columnField.js";
import {getOrderPage} from "@/api/standard/index.js";
import {postFile} from "@utils/service/index.js";
import {getManyDictItems} from "@/api/system/dict.js";
import {message} from "ant-design-vue";
const { dataList, query, loading, page, search, reset, onPageChange } = useSearchTable({
  searchAPI: getOrderPage,
  queryFactory: () => ({
  }),
  beforeSearch: () => {
    //处理日期
    // console.log(query.value.time)
      if(query.value.time){
        query.value.startTime = query.value.time[0]
        query.value.endTime = query.value.time[1]
      }else{
        delete query.value.startTime
        delete query.value.endTime
      }
      if(query.value.orderId){
        query.value.orderId = query.value.orderId.trim()
      }
      if(query.value.billingEmail){
        query.value.billingEmail = query.value.billingEmail.trim()
      }
  },
  afterSearch: () => {
    dataList.value.forEach(item => {
      if(item.skuItemList == null){
        item.skuItemList = [
          {
            productSku:"12131313",
            qty:1,
          },
          {
            productSku:"5846113",
            qty:2,
          }
        ]
      }
      if(item.addressItem == null){
        item.addressItem = {
          shippingCountry:"DE",
          childAddressItem:{
            shippingStreetLine1:"A",
            shippingStreetLine2:"B",
            shippingCity:"C",
            shippingRegion:"D",
            shippingPostcode:"E",
          },
          shippingCustName:"Linard Kando",
          shippingTelephone:"015731732855",
          shippingEmail:"linard.kando@hotmail.com"
        }
      }
      if(item.orderSourceItem == null){
        item.orderSourceItem = {
          sensorsUserId:12131231313,
          protect:{
            source:"A",
            medium:"A",
            campaign:"A",
          },
          first:{
            source:"B",
            medium:"B",
            campaign:"B",
          },
          latest:{
            source:"C",
            medium:"C",
            campaign:"C",
          }
        }
      }
    })
    handleDataList.value = dataList.value
    handleDataList.value.forEach(item => {
      item.sourceAndProductSkuItem = {
        ...item.sourceAndProductSkuItem,
        showMoreSkuItem:undefined,
        showMoreSourceSku:undefined,
      }
    })
    console.log(handleDataList.value)
  }
})
const columns = [
  {
    title: '基本信息',
    dataIndex: 'basicItem',
    width: 150,
    fixed: 'center'
  },
  {
    title: '金额',
    dataIndex: 'accountItem',
    width: 120,
    fixed: 'center'
  },
  {
    title: '商品',
    dataIndex: 'skuItemList',
    width: 100,
    fixed: 'center'
  },
  {
    title: '地址',
    dataIndex: 'addressItem',
    width: 120,
    fixed: 'center'
  },
  {
    title: '归因',
    dataIndex: 'orderSourceItem',
    width: 180,
    fixed: 'center'
  },
]
const handleDataList = ref([])

const formItems = ref([
  {
    label: '平台',
    field: 'platform',
    type: 'select',
    options: []
  },
  {
    label: '订单',
    field: 'orderId',
    type: 'input'
  },
  {
    label: '站点',
    field: 'site',
    type: 'select',
    options: []
  },
  {
    label: '下单邮箱',
    field: 'billingEmail',
    type: 'input'
  },
  {
    label: '下单时间',
    field: 'time',
    type: 'rangePicker',
    defaultValue: [],
    showTime:false,
  },
  {
    label: '状态',
    field: 'orderStatus',
    type: 'select',
    options: []
  },
  {
    label: 'SKU',
    field: 'sku',
    type: 'input',
  },
  {
    label: '用户姓名',
    field: 'shippingCustName',
    type: 'input',
  },
  {
    label: '是否有重发单',
    field: 'hasReloadFlag',
    type: 'select',
    options:[]
  },
])
const btnLoading = ref(false)
const showMoreSkuItem = (record,type,item) => {
  if(type === 'open'){
      record.sourceAndProductSkuItem[item] = true
  }else if (type === 'close') {
      record.sourceAndProductSkuItem[item] = false
  }
}
/**
 * 判断是否显示展开按钮
 * @param record  行数据
 * @param type  显示或者关闭
 * @param list  数组
 * @returns {boolean} true 显示 false 不显示
 */
const openShowMoreSkuItem = (record,type,list) =>{
    // 如果数组长度大于3 并且 显示展开按钮未定义或者是false 则显示
    if(record.sourceAndProductSkuItem[list].length > 10 && (record.sourceAndProductSkuItem[type] === undefined || record.sourceAndProductSkuItem[type] === false)){
      return true
      // 如果数组长度小于等于3则不显示
    }else if(record.sourceAndProductSkuItem[type] === true){
      return false
    }
}
/**
 * 判断是否显示收起按钮
 * @param record  行数据
 * @param type  显示或者关闭
 * @returns {boolean} true 显示 false 不显示
 */
const closeShowMoreSkuItem = (record,type) =>{
  if(record.sourceAndProductSkuItem[type] === true){
    return true
  }else if(record.sourceAndProductSkuItem[type] === false ){
    return false
  } else if (record.sourceAndProductSkuItem[type] === undefined){
    return false
  }
}
const toExport = async () => {
  try{
    let obj = query.value
    if(obj.time){
      if(obj.time[0] && obj.time[1] && isWithinAYear(obj.time[0], obj.time[1])){
        obj.startTime = obj.time[0]
        obj.endTime = obj.time[1]
      }else{
        return message.error("请选择近一年内的时间")
      }
    }else{
      delete obj.startTime
      delete obj.endTime
      return message.error("请选择导出时间")
    }
    if(obj.orderId){
      obj.orderId = obj.orderId.trim()
    }
    if(obj.billingEmail){
      obj.billingEmail = obj.billingEmail.trim()
    }
    btnLoading.value = true
    const res = await postFile('/order/export','post',obj,"标准化订单列表.xlsx")
  }catch(e){

  }finally {
    btnLoading.value = false
  }
}
function isWithinAYear(dateStr1, dateStr2) {
  const date1 = new Date(dateStr1);
  const date2 = new Date(dateStr2);
  const oneYear = 366 * 24 * 60 * 60 * 1000; // 近似一年的毫秒数
  const diff = Math.abs(date2 - date1);
  return diff < oneYear;
}
const init = async () => {
  try{
    const res = await getManyDictItems({
      dictCodeList:"orderPlatform,site,orderStatus,is_open"
    })
    formItems.value[0].options = res.result.orderPlatform
    formItems.value[2].options = res.result.site
    formItems.value[5].options = res.result.orderStatus
    formItems.value[8].options = res.result.is_open
  }catch (e){
    console.log(e)
  }
}
onMounted(()=>{
  init()
})
</script>
<script>
export default {
  name: 'orderStandardization-orderList'
}
</script>
<style lang="less" scoped>
  :deep(.ant-descriptions-row >td) {
    padding: 1px;
  }
</style>

